<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="10"
          accept=".jpg ,.png  ,.gif  ,.jpeg  ,.bmp  ,.xlsx  ,.xls"
          :action="upload.url"
          :headers="upload.headers"
          :file-list="upload.fileList"
          :multiple="multiple"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-button
        class="upload-down"
        size="small"
        type="primary"
        icon="el-icon-down"
        :disabled="multiple"
        @click="handleDownload"
        v-hasPermi="['system:info:down']"
      >下载</el-button>

      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="handleDelete"
        v-hasPermi="['system:info:remove']"
      >删除</el-button>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="id" align="center" prop="fileId" />-->
      <el-table-column label="文件名" align="center" prop="fileName" />
      <el-table-column label="文件路径" align="center" prop="filePath" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件路径" prop="filePath">
          <el-input v-model="form.filePath" placeholder="请输入文件路径" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listFile, getFile, delFile, addFile, updateFile, uploadFiles,getFiles} from "@/api/system/file";
import {getToken} from "@/utils/auth";


export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件信息表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        /** 文件名称  */
        fileName: null,
        /** 文件路径  */
        filePath: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken(), 'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundary7TMYhSONfkAM2z3a'},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploads",
        // 上传的文件列表
        fileList: []
      },
      fileIds:[]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 多下载触发方法 包括单下载  */
    handleDownload(){
      /** 获取多选框选中的id  */
       const ids = this.ids;
       for (let i = 0;i <= ids.length-1; ++i){
         getFiles(ids[i]).then(response => {
           if(response.code == "200"){
             /** 文件名  */
             const name = response.data[0].fileName;
             /** 文件路径  */
             const url = response.data[0].filePath;
             /** 判断数据源是否为空  */
              if (url != null){
                /** 创建隐藏的可下载链接  */
                const suffix = url.substring(url.lastIndexOf("."), url.length);
                const a = document.createElement('a')
                /** 设置下载的文件名  */
                a.setAttribute('download', name + suffix)
                /** 设置在新窗口打开  */
                a.setAttribute('target', '_blank')
                /** 设置下载的路径  */
                a.setAttribute('href', url)
                /** 点击下载  */
                a.click()
              }
           }
         })
       }
      },
    /** 点击上传服务器触发的方法 */
    submitUpload() {
      /** 把选取的文件存在upload中的fileList里  */
      this.upload.fileList = this.$refs.upload.uploadFiles;
      const formData = new FormData();
      for (let i = 0; i < this.upload.fileList.length; i++) {
        formData.append('file', this.upload.fileList[i].raw);
      }
      uploadFiles(formData).then(response => {
        // console.log(response)
        if(response.code === 200){
          console.log(response)
          console.log("打印响应信息--------->")
          console.log(response)

          this.$message({
            message: '上传成功',
            type: 'success'
          });
        }else {
          this.$message({
            message: '上传失败',
            type: 'error'
          });
        }
      });
      this.$refs.upload.submit();
    },
    /** 查询文件信息列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        filePath: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getFile(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件信息编号为"' + fileIds + '"的数据项？').then(function() {
        return delFile(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('interview/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.upload-demo{
  float: right;
  margin-left: 25px;
}
/* .upload-down{ */
/*   float: right; */
/*   margin-right: 520px; */
/* } */
</style>
